# -*- coding: utf-8 -*-
__author__ = 'lztkdr'
__date__ = '2019/7/29 8:46'


'''
封装python 实体Base 类
采用sqlalchemy定义实体类，进行ORM操作
依赖库：
   pip install pymysql
   pip install sqlalchemy
'''

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative  import declarative_base
# 导入数据库配置字典
from GuaZi_Spider.settings import MYSQL_STR
import json

#创建orm基类
ORM_BASE = declarative_base()

# 创建引擎
# ORM_Engine = create_engine(MYSQL_STR)

# echo参数为True时，会显示每条执行的SQL语句，调试的时候，可以开启。
ORM_Engine = create_engine(MYSQL_STR, echo=True, encoding='utf-8', convert_unicode=True,pool_size=100, pool_recycle=3600)

##########################################################################################################################################
from sqlalchemy import DateTime,Numeric

def _gen_tuple(self):
    def convert_datetime(value):
        if value:
            return value.strftime("%Y-%m-%d %H:%M:%S")
        else:
            return ""

    for col in self.__table__.columns:
        if isinstance(col.type, DateTime):
            value = convert_datetime(getattr(self, col.name))
        elif isinstance(col.type, Numeric):
            value = float(getattr(self, col.name))
        else:
            value = getattr(self, col.name)
        yield (col.name, value)


def to_dict(self):
    return dict(self._gen_tuple())


def to_json(self):
    return json.dumps(self.to_dict(),ensure_ascii= False,indent=2)

ORM_BASE._gen_tuple = _gen_tuple
ORM_BASE.to_dict = to_dict
ORM_BASE.to_json = to_json

##########################################################################################################################################

